package com.eastshop.user.service;

import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import com.eastshop.user.dao.UserDao;
import com.eastshop.user.vo.User;
import com.eastshop.utils.MailUitls;
import com.eastshop.utils.PageBean;
import com.eastshop.utils.UUIDUtils;
/**
 * 用户模块的Service类
 * @author admin
 *
 */
@Transactional
public class UserService {

	// Service层注入userDao
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	// Service层用户登录的方法
	public User login(User user) {
		return userDao.find(user);
	}

	// Service层根据用户名查找用户
	public User findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	// Service层保存用户的信息
	public void save(User user) {
		//设置用户状态
		user.setState(0); //0：未激活    1：激活
		//生成激活码
		String code = UUIDUtils.getUUID()+UUIDUtils.getUUID();
		user.setCode(code);
		//将激活码发送到指定邮箱
		MailUitls.sendMail(user.getEmail(), code);
		//保存用户信息
		userDao.save(user);
	}

	// Service层根据激活码查找用户
	public User findByCode(String code) {
		return userDao.findByCode(code);
	}

	// Service层更新用户的信息
	public void update(User user) {
		userDao.update(user);
	}

	// Service层分页查询用户的信息
	public PageBean<User> findAllWithPage(int page) {
		PageBean<User> pageBean = new PageBean<User>();
		// 设置当前的记录数
		pageBean.setPage(page);
		// 设置每页显示的记录数
		int limit = 5;
		pageBean.setLimit(limit);
		// 设置总的记录数
		int totalCount = userDao.findCount();
		pageBean.setTotalCount(totalCount);
		// 设置总的页数
		int totalPage = 0;
		if(totalCount % limit == 0){
			totalPage = totalCount / limit;
		}else{
			totalPage = totalCount / limit + 1;
		}
		pageBean.setTotalPage(totalPage);
		// 设置每页显示的数据集合
		int begin = (page -1) * limit;
		List<User> list = userDao.findAllWithPage(begin, limit);
		pageBean.setList(list);
		return pageBean;
	}

	// Service层根据用户id查询用户的方法
	public User findByUid(Integer uid) {
		User user = userDao.findByUid(uid);
		return user;
	}
	
	// Service层删除用户的方法
	public void delete(User currUser) {
		userDao.delete(currUser);
	}
	
	
}
